<template>
  <div>
    <div class="progress_item">
      <van-progress inactive :percentage="percent" :show-pivot="false" />
    </div>
    <div :key="item.id" class="head_item">
      {{ index + 1 }}.{{ item.question }}
    </div>
    <div class="context_item">
      <!-- 单选框 -->
      <van-radio-group v-model="selectedRatio" v-show="item.answer.length == 1">
        <div :style="selectd_item1">
          <van-radio name="A" @click="radioHandler"
            ><div ref="radio_item1">{{ item.item1 }}</div></van-radio
          >
        </div>
        <div :style="selectd_item2">
          <van-radio name="B" @click="radioHandler"
            ><div ref="radio_item2">{{ item.item2 }}</div></van-radio
          >
        </div>
        <div :style="selectd_item3">
          <van-radio name="C" @click="radioHandler"
            ><div ref="radio_item3">{{ item.item3 }}</div></van-radio
          >
        </div>
        <div :style="selectd_item4" v-if="item.item4">
          <van-radio name="D" @click="radioHandler"
            ><div ref="radio_item4">{{ item.item4 }}</div></van-radio
          >
        </div>
      </van-radio-group>
      <!-- 多选框 -->
      <van-checkbox-group
        v-model="selectedChecked"
        v-show="item.answer.length > 1"
      >
        <div :style="selectd_item1">
          <van-checkbox name="A" @click="checkHandler" shape="square"
            ><div ref="check_item1">{{ item.item1 }}</div></van-checkbox
          >
        </div>
        <div :style="selectd_item2">
          <van-checkbox name="B" @click="checkHandler" shape="square"
            ><div ref="check_item2">{{ item.item2 }}</div></van-checkbox
          >
        </div>
        <div :style="selectd_item3">
          <van-checkbox name="C" @click="checkHandler" shape="square"
            ><div ref="check_item3">{{ item.item3 }}</div></van-checkbox
          >
        </div>
        <div :style="selectd_item4" v-if="item.item4">
          <van-checkbox name="D" @click="checkHandler" shape="square"
            ><div ref="check_item4">{{ item.item4 }}</div></van-checkbox
          >
        </div>
      </van-checkbox-group>
    </div>
    <div class="func_item">
      <!-- 功能区，有提交，收藏，下一题，上一题等各种按钮 -->
      <div class="func_item_left">
        <div class="func_item_button">
          <van-button
            :type="tappedfalg ? 'warning' : 'info'"
            :icon="tappedfalg ? 'checked' : 'info'"
            size="small"
            @click="tap"
            >标 记</van-button
          >
        </div>
        <div class="func_item_button">
          <van-button
            type="info"
            icon="success"
            size="small"
            @click="submitExam"
            >交 卷</van-button
          >
        </div>
      </div>
      <div class="picker_box" @click="showPopup">
        {{ index + 1 }}/{{ total }}
      </div>
      <div class="func_item_right">
        <div class="func_item_button">
          <van-button type="info" icon="arrow-left" size="small" @click="prev"
            >上一题</van-button
          >
        </div>
        <div class="func_item_button">
          <van-button type="info" icon="arrow" size="small" @click="next"
            >下一题</van-button
          >
        </div>
      </div>
    </div>
    <van-popup v-model="show" position="bottom"
      ><van-picker
        title="选择题目"
        show-toolbar
        :columns="columns"
        @confirm="onConfirm"
        @cancel="onCancel"
        @change="onChange"
    /></van-popup>
  </div>
</template>

<script>
import selfTestApi from "@/api/selfTest/index";
import zhiZhaoApi from "@/api/questionItem/questionItem";
import { Dialog } from "vant";
import { Notify } from "vant";
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      heigth1: 40,
      heigth2: 40,
      heigth3: 40,
      heigth4: 40,
      questionItemId: "",
      columns: [],
      show: false,
      index: 0,
      total: 0,
      items: [], //所有的题
      item: {
        subject: "",
        question: "",
        item1: "",
        item2: "",
        item3: "",
        item4: "",
        answer: "",
      }, //单独的某一道题
      selectedRatio: "", //选择单选题的答案
      selectedChecked: [], //选择多选题的答案
      allAnswers: [], //选择的所有题目的答案
      tapIndex: [], //标记的题目的索引
      tappedfalg: false, //表示某一题是否被标记过的索引
      percent: 0, //进度条
      testTime: 5, //考试时间
    };
  },
  methods: {
    /**
     * 监听当前页面是否离开
     * @param {} e
     */
    handleVisiable(e) {
      switch (e.target.visibilityState) {
        case "prerender":
          console.log("网页预渲染，内容不可见");
          break;
        case "hidden":
          console.log("内容不可见，处理后台、最小化、锁屏状态");
          alert("警告！你已经离开当前答题页面，5秒后自动交卷！");
          setTimeout(() => {
            this.submitExam();
          }, 5000);
          break;
        case "visible":
          console.log("处于正常打开");
          break;
      }
    },
    radioHandler() {
      for (let index = 0; index < 4; index++) {
        this.allAnswers[this.index][index] = "";
      }
      this.setAllAnswers(this.selectedRatio);
    },
    setAllAnswers(item) {
      switch (item) {
        case "A":
          this.allAnswers[this.index][0] = item;
          break;
        case "B":
          this.allAnswers[this.index][1] = item;
          break;
        case "C":
          this.allAnswers[this.index][2] = item;
          break;
        case "D":
          this.allAnswers[this.index][3] = item;
          break;
        default:
          // do something
          break;
      }
    },
    checkHandler() {
      for (let index = 0; index < 4; index++) {
        this.allAnswers[this.index][index] = "";
      }
      for (let index = 0; index < this.selectedChecked.length; index++) {
        const element = this.selectedChecked[index];
        this.setAllAnswers(element);
      }
    },
    /**
     * 1.计算分数
     * 2.把计算出的分数传给后端服务器
     */
    submitExam() {
      //先看看有没有标记的题目
      if (this.tapIndex.length > 0) {
        Dialog.confirm({
          title: "确认框",
          message: "还有标记的题目哦，不去看看吗",
          confirmButtonText: "检查一下",
          cancelButtonText: "直接交卷",
        })
          .then(() => {
            this.item = this.items[this.tapIndex[0]];
            this.index = this.tapIndex[0];
          })
          .catch(() => {
            this.submitTitle();
          });
      } else {
        Dialog.confirm({
          title: "确认框",
          message: "是否确认交卷？",
          cancelButtonText: "检查一下",
          confirmButtonText: "直接交卷",
        }).then(() => {
          this.submitTitle();
        });
      }
    },
    //提交试卷的方法
    submitTitle: async function () {
      let rightNum = 0;
      for (let i = 0; i < this.allAnswers.length; i++) {
        let element = this.allAnswers[i].filter((a) => a != "");
        element.sort();
        const selected = element.join("+");
        if (selected == this.items[i].answer) {
          rightNum++;
        }
      }
      const score = Math.round((rightNum / this.total) * 100);
      //这里把分数提交给数据库就行了
      clearInterval(this.setInter);
      let ids = new Array();
      for (let index = 0; index < this.items.length; index++) {
        const element = this.items[index];
        ids.push(element.id);
      }
      //如果是教师出题进入此页面的话，没有type属性，此时type是null
      if (!this.$route.query.type) {
        const response = await zhiZhaoApi.submit(
          score,
          Math.round((this.percent * this.testTime) / 100),
          this.questionItemId,
          this.name,
          this.allAnswers,
          ids,
          this.$route.query.title
        );
        Notify({ type: "primary", message: `${response.message}` });
        //todo 这里到时候把页面关了
        this.$router.push("/testResult/index");
      } else {
        //否则如果有type属性，表明是用户自我测试
        const response = await selfTestApi.submit(
          score,
          Math.round((this.percent * this.testTime) / 100),
          this.questionItemId,
          this.name,
          this.allAnswers,
          ids
        );
        Notify({ type: "primary", message: `${response.message}` });
        //todo 这里还要做相应的页面变化，比如关闭当前页面，跳转到回顾试卷页面等等
        this.$router.push("/learn/index");
      }
    },
    /**
     * 标记该题目的索引
     */
    tap() {
      if (!this.tappedfalg) {
        this.tapIndex.push(this.index);
        this.tappedfalg = true;
      } else {
        this.tapIndex = this.tapIndex.filter((e) => e !== this.index);
        this.tappedfalg = false;
      }
    },
    next() {
      if (this.index == this.total - 1) {
        this.$message({
          message: "已经是最后一题了！",
          type: "error",
        });
        return;
      }
      this.index = this.index + 1;
    },
    prev() {
      if (this.index == 0) {
        this.$message({
          message: "已经是第一题了！",
          type: "error",
        });
        return;
      }
      this.index = this.index - 1;
    },
    showPopup() {
      this.show = true;
    },
    /**
     * 当获取到考卷后，初始化一些数据
     * 1.初始化一个计时器
     * 2.初始化选择答案的数组
     */
    init() {
      let t1 = 1;
      this.setInter = setInterval(() => {
        t1++;
        this.percent = (t1 / this.testTime) * 100;
        if (Math.round(this.percent) == 100) {
          this.submitExam();
        }
      }, 1000);
      for (let index = 0; index < this.total; index++) {
        let arr = new Array();
        arr.push("");
        arr.push("");
        arr.push("");
        arr.push("");
        this.allAnswers.push(arr);
      }
    },
    onConfirm(value, index) {
      this.index = index;
      this.show = false;
    },
    onCancel() {
      this.show = false;
    },
    onChange(picker, value, index) {
      this.index = index;
      this.item = this.items[this.index];
      this.show = false;
    },
    /**
     * 计算单选框，复选框的文字的高度
     */
    calculateTextLines() {
      //如果有选项4为非英语M9
      if (this.item.item4) {
        let van1;
        let van2;
        let van3;
        let van4;
        this.$nextTick(() => {
          if (this.item.answer.length > 1) {
            van1 = this.$refs.check_item1;
            van2 = this.$refs.check_item2;
            van3 = this.$refs.check_item3;
            van4 = this.$refs.check_item4;
          } else {
            van1 = this.$refs.radio_item1;
            van2 = this.$refs.radio_item2;
            van3 = this.$refs.radio_item3;
            van4 = this.$refs.radio_item4;
          }
          //这里为了美观，在刚进入页面时，如果选择框的高度为0，也就是第一次进入页面时，此时由于其高度为0，给他一个默认高度40
          this.heigth1 =
            van1.clientHeight == 0
              ? van1.clientHeight + 40
              : van1.clientHeight + 20;
          this.heigth2 =
            van2.clientHeight == 0
              ? van2.clientHeight + 40
              : van2.clientHeight + 20;
          this.heigth3 =
            van3.clientHeight == 0
              ? van3.clientHeight + 40
              : van3.clientHeight + 20;
          this.heigth4 =
            van4.clientHeight == 0
              ? van4.clientHeight + 40
              : van4.clientHeight + 20;
        });
      } else {
        //如果无选项4为英语M9
        let van1;
        let van2;
        let van3;
        this.$nextTick(() => {
          if (this.item.answer.length > 1) {
            van1 = this.$refs.check_item1;
            van2 = this.$refs.check_item2;
            van3 = this.$refs.check_item3;
          } else {
            van1 = this.$refs.radio_item1;
            van2 = this.$refs.radio_item2;
            van3 = this.$refs.radio_item3;
          }
          //这里为了美观，在刚进入页面时，如果选择框的高度为0，也就是第一次进入页面时，此时由于其高度为0，给他一个默认高度40
          this.heigth1 =
            van1.clientHeight == 0
              ? van1.clientHeight + 40
              : van1.clientHeight + 20;
          this.heigth2 =
            van2.clientHeight == 0
              ? van2.clientHeight + 40
              : van2.clientHeight + 20;
          this.heigth3 =
            van3.clientHeight == 0
              ? van3.clientHeight + 40
              : van3.clientHeight + 20;
        });
      }
    },
  },
  watch: {
    /**
     * 当页面发生改变时
     * 1.检测该页面的索引是否在tapIndex中
     * 2.重新渲染新的页面，生成新的题目
     * 3.以前做过的题目选项要回显
     * @param {index索引} newVal
     */
    index(newVal) {
      this.selectedRatio = "";
      this.selectedChecked = [];
      this.item = this.items[newVal];
      if (this.tapIndex.includes(newVal)) {
        this.tappedfalg = true;
      } else {
        this.tappedfalg = false;
      }
      const res = this.allAnswers[newVal].filter((a) => a != "");
      if (this.items[newVal].answer.length > 1) {
        //多选题
        this.selectedChecked = res;
      } else {
        //单选题
        this.selectedRatio = res[0];
      }
      this.calculateTextLines();
    },
  },
  computed: {
    ...mapGetters(["name"]),
    selectd_item1() {
      return {
        display: "flex",
        "align-items": "center",
        height: `${this.heigth1}px`,
      };
    },
    selectd_item2() {
      return {
        display: "flex",
        "align-items": "center",
        height: `${this.heigth2}px`,
      };
    },
    selectd_item3() {
      return {
        display: "flex",
        "align-items": "center",
        height: `${this.heigth3}px`,
      };
    },
    selectd_item4() {
      return {
        display: "flex",
        "align-items": "center",
        height: `${this.heigth4}px`,
      };
    },
  },
  mounted() {
    // document.addEventListener("visibilitychange", this.handleVisiable);
  },
  created() {
    /**
     * 如果是重定向到此页面，比如用户复制了某网址进入的此页面
     * 此时是无法从路由中获得参数的，为了防止报错
     * 一旦重定向过来，都让其回到随堂测验的页面
     */
    if (Object.keys(this.$route.query).length == 0) {
      this.$router.push({
        path: `/exam/startExam`,
      });
      return;
    }
    const questionItemId = this.$route.query.questionItemId;
    //如果是教师出题进入此页面的话，没有type属性，此时type是null
    const type = this.$route.query.type;
    if (!type) {
      this.questionItemId = questionItemId;
      zhiZhaoApi
        .batchGet(questionItemId)
        .then((res) => {
          this.items = res.data.result;
          this.testTime = res.data.time;
          this.item = this.items[0];
          for (let index = 0; index < this.items.length; index++) {
            const element = this.items[index];
            let column = index + 1 + "." + element.question;
            this.columns.push(column);
          }
          this.total = this.columns.length;
          this.init();
        })
        .catch(() => {
          this.$router.push({
            path: `/exam/startExam`,
          });
        });
    } else {
      //如果自己出题进入此页面有type属性
      this.questionItemId = questionItemId;
      selfTestApi.batchGet(questionItemId).then((res) => {
        this.items = res.data.result;
        this.testTime = res.data.time;
        this.item = this.items[0];
        for (let index = 0; index < this.items.length; index++) {
          const element = this.items[index];
          let column = index + 1 + "." + element.question;
          this.columns.push(column);
        }
        this.total = this.columns.length;
        this.init();
      });
    }
  },
  beforeDestroy() {
    clearInterval(this.setInter);
    // document.removeEventListener("visibilitychange", this.handleVisiable);
  },
};
</script>

<style scoped>
.progress_item {
  margin-top: 5px;
  height: 20px;
  width: 95%;
  font-size: 15px;
}

.head_item {
  margin-top: 20px;
  height: 180px;
}

.context_item {
  height: 400px;
  overflow: auto;
}

.func_item {
  display: flex;
  justify-content: center;
}

.func_item_button {
  margin-left: 1px;
  margin-right: 1px;
}
.func_item_left {
  width: 29%;
  display: flex;
  justify-content: left;
}

.func_item_right {
  width: 39%;
  display: flex;
  justify-content: right;
}

.picker_box {
  background-color: rgb(191, 203, 203);
  border-radius: 2px;
  width: 30%;
  margin-right: 2px;
  margin-left: 2px;
  text-align: center; /* 水平居中对齐 */
  font-size: 20px; /* 字体大小 */
}
</style>
